//  this library.
import 'package:flutter/material.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/ienum/practice/ct_enum.dart';
import 'package:hktk_app/ienum/question/answer_type_enum.dart';
import 'package:hktk_app/ienum/question/collect_type_enum.dart';
import 'package:hktk_app/ienum/question/question_type_enum.dart';
import 'package:hktk_app/model/practice/practice_question_model.dart';
import 'package:hktk_app/model/question/paper_data_model.dart';
import 'package:hktk_app/model/question/question_data_model.dart';
import 'package:hktk_app/model/subject/question_collection_model.dart';
import 'package:hktk_app/model/subject/records_model.dart';
import 'package:hktk_app/pages/question/child/question_exam_page.dart';
import 'package:hktk_app/util/my_util.dart';

/// 随机组卷试题页面显示
class RandomQuestionPage extends StatefulWidget {
  final RecordsModel recordsModel;

  const RandomQuestionPage({
    super.key,
    required this.recordsModel,
  });

  @override
  State<RandomQuestionPage> createState() => _RandomQuestionPageState();
}

class _RandomQuestionPageState extends State<RandomQuestionPage> {
  /// 试题数据集合
  late Map<String, QuestionDataModel> _dataMap;

  @override
  Widget build(BuildContext context) {
    debugPrint("randomQuestionPage 页面 -> build 方法执行 ===> ");
    debugPrint("");
    return QuestionExamPage(
      paperInit: _initData,
      quesInit: _quesInit,
      type: QuestionTypeEnum.exam,
    );
  }

  /// 初始化加载数据方法
  Future<Map<String, dynamic>> _initData() async {
    Map<String, dynamic> map = {};
    try {
      PaperDataModel data = _getPaperData();
      map["data"] = data;
      map["suc"] = true;
    } catch (e) {
      debugPrint("randomQuestionPage 页面 -> 初始化试卷数据发生异常 ===> $e");
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        debugPrint("randomQuestionPage 页面 -> dao异常 ===> ${e.msg}");
        map["msg"] = e.msg;
      }
    }
    return map;
  }

  /// 获取试题数据相关方法
  PaperDataModel _getPaperData() {
    // 答题卡相关数据
    List<DtkInfoModel> dtkList = [];
    // 大题相关数据
    List<BogInfoModel> bogList = [];
    // 试题总题数
    int ii = 0;
    // 上一次所做的最后一个试题相关下标
    int index = 0;
    _dataMap = {};
    List<ContentCollection> content = widget.recordsModel.content!;
    for (int i = 0; i < content.length; i++) {
      ContentCollection collection = content[i];
      bogList.add(BogInfoModel(
        name: collection.tyName!,
        type: collection.qs![0].firstType!,
        total: collection.qs?.length ?? 0,
        dtkList: [],
      ));
      List<PracticeQuestionModel> qsList = collection.qs!;
      for (int j = 0; j < qsList.length; j++) {
        PracticeQuestionModel qModel = qsList[j];
        // 试题数据
        QuestionDataModel qDataModel = MyUtil.getQuestionData(qModel);
        _dataMap[qModel.id!] = qDataModel;
        if (widget.recordsModel.lastId == qModel.id) {
          index = ii;
        }
        // 收藏
        CollectTypeEnum type = CollectTypeEnum.def;
        if (qModel.collect != null && qModel.collect!) {
          type = CollectTypeEnum.suc;
        }
        // 本题是否已做
        AnswerTypeEnum ansType = AnswerTypeEnum.notDone;
        List<String> ans = [];
        if (qModel.record != null) {
          RecordModel record = qModel.record!;
          ansType = AnswerTypeEnum.success;
          ans = MyUtil.getUserAnsList(record.as, qModel.firstType!);
        }

        // 答题卡相关数据
        dtkList.add(DtkInfoModel(
          index: ii,
          id: qModel.id!,
          type: qModel.firstType!,
          sign: qModel.sign!,
          collType: type,
          ansType: ansType,
          answerBase64: qModel.answerBase64,
          st: qDataModel.stem,
          userAns: ans,
        ));
        ii++;
      }
    }
    return PaperDataModel(
      name: widget.recordsModel.name!,
      id: widget.recordsModel.id!,
      collectId: widget.recordsModel.id!,
      lastIndex: index,
      dtkList: dtkList,
      bogDtkList: bogList,
      rType: CtEnum.paperRecordRandomFormPaper,
      examTime: widget.recordsModel.examTime ?? 0,
      startDate: DateTime.now().millisecondsSinceEpoch,
    );
  }

  /// 加载试题数据方法
  Future<Map<String, dynamic>> _quesInit(String qId, String cid) async {
    QuestionDataModel? dataModel = _dataMap[qId];
    if (dataModel == null) {
      debugPrint("randomQuestionPage 页面 -> 加载试题数据方法发生异常 ===> 未加载到对应试题数据");
      return {"suc": false, "msg": "未知错误，请重试"};
    }
    return {"suc": true, "data": dataModel};
  }
}
